package com.drinkian.utils;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 写数据
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(String key, Object value) {
        boolean result = false;
        if (value == null) {
            return result;
        }
        try {
            redisTemplate.opsForValue().set(key,value);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 带失效时间的写入
     *
     * @param key
     * @param value
     * @param expireTime
     * @param timeUnit
     * @return
     */
    public boolean set(String key, Object value, Long expireTime, TimeUnit timeUnit) {
        boolean result = false;
        if (value == null) {
            return result;
        }
        try {
            redisTemplate.opsForValue().set(key, value);
            redisTemplate.expire(key, expireTime, timeUnit);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public <T>T get(String key, Class<T> tClass) {
        if(key == null) {
            return null;
        }
//        这是个半成品对象，本质是LinkedHashMap
        Object jsonObject = redisTemplate.opsForValue().get(key);
        String jsonString = JSON.toJSONString(jsonObject);
        T javaObject = JSON.parseObject(jsonString, tClass);
        return javaObject;
    }

    public boolean del(String key){
        return redisTemplate.delete(key);
    }
}